<template>
  <van-field
    v-model="value"
    :name="params.value"
    :label="params.label"
    :placeholder="params.placeholder || '请选择'"
    :color="formParams.color"
    v-bind="{ ...params.bind }"
    is-link
    readonly
    @click="!params.refuseEvent && (showCalendar = true)"
  />
  <van-calendar
    v-bind="{ ...params.bind }"
    v-model:show="showCalendar"
    @confirm="getCalendarData"
  />
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import regexFunctions from '@/utils/regex.js'

const showCalendar = ref(false)

// 校验并返回第一个错误
const validateByRegex = (input, regex) => {
  let flag = ''
  for (const element of regex) {
    if (!regexFunctions[element.regFun](input)) {
      flag = element.msg
      break
    }
  }
  return flag
}

const props = defineProps(['params', 'modelValue', 'formParams'])

const value = ref(props.modelValue)

const emits = defineEmits(['update:modelValue', 'validate', 'getText'])

const getCalendarData = data => {
  if (value.value && props.params.event) {
    props.params.event.funcName()
  }
  value.value =
    data &&
    `${data.getFullYear()}/${data.getMonth() + 1 < 10 ? '0' + (data.getMonth() + 1) : data.getMonth() + 1}/${data.getDate() < 10 ? '0' + data.getDate() : data.getDate()}`
  showCalendar.value = false
  // change触发时 向父组件返回值 并将数据校验暴露出来
  data &&
    emits(
      'update:modelValue',
      data &&
        `${data.getFullYear()}${data.getMonth() + 1 < 10 ? '0' + (data.getMonth() + 1) : data.getMonth() + 1}${data.getDate() < 10 ? '0' + data.getDate() : data.getDate()}`,
    )
  if (props.params.regex) {
    // 校验数据是否符合规则
    const res = validateByRegex(
      data &&
        `${data.getFullYear()}/${data.getMonth() + 1 < 10 ? '0' + (data.getMonth() + 1) : data.getMonth() + 1}/${data.getDate() < 10 ? '0' + data.getDate() : data.getDate()}`,
      props.params.regex,
    )
    emits('validate', {
      name: props.params.value,
      validateRes: res === '',
      validateMsg: res,
    })
  }
}

onMounted(() => {
  getCalendarData()
})
watch(
  () => props.modelValue,
  newVal => {
    value.value =
      newVal &&
      `${newVal.slice(0, 4)}/${newVal.slice(4, 6)}/${newVal.slice(6, 8)}`
  },
)
</script>
